//
//  OSTopicViewController.m
//  百思不得姐
//
//  Created by PushMeBaby on 16/3/2.
//  Copyright © 2016年 CoderC. All rights reserved.
//

#import "OSTopicViewController.h"
#import "OSTopicCell.h"
#import "OSTopic.h"
#import "OSCommentViewController.h"

#import "OSNewViewController.h"
@interface OSTopicViewController ()


{

    NSIndexPath *currentIndexPath;
    BOOL isSmallScreen;
}
@property (nonatomic,strong)NSMutableDictionary *params;

@property (nonatomic,copy)NSString *maxtime;

@property (nonatomic,strong)NSMutableArray *topics;


@property (nonatomic,assign)NSInteger page;

@property (nonatomic,weak)NSIndexPath *currentIndexPath;

@property (nonatomic,strong)OSTopicCell *currentCell;


@end

@implementation OSTopicViewController

static NSString *const OSTopicCellId = @"topic";

-(NSMutableArray *)topics{
    if (!_topics) {
        _topics = [NSMutableArray array];
    }
    return _topics;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupRefresh];
    [self setupTableView];
}
-(void)setupTableView{
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top = OSTitilesViewY + OSTitilesViewH;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"OSTopicCell" bundle:nil] forCellReuseIdentifier:OSTopicCellId];
}


-(void)setupRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    self.tableView.header.autoChangeAlpha = YES;
    [self.tableView.header beginRefreshing];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
}

-(NSString *)a{
    return [self.parentViewController isKindOfClass:[OSNewViewController class]] ? @"newlist" : @"list";
}

-(void)loadMoreTopics{
    [self.tableView.header endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    NSInteger page = self.page + 1;
    params[@"page"] = @(page);
    params[@"maxtime"] = self.maxtime;
    self.params = params;
    
    
    
    [[AFHTTPSessionManager manager]GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *  task, id   responseObject) {
        
        if (self.params != params) {
            return ;
        }
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        NSArray *newTopics = [OSTopic objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:newTopics];
     

        
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
        self.page = page;
        
        
        
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        
        if (self.params != params) {
            return ;
        }
        
        [self.tableView.footer endRefreshing];
        
    }];
    
}
-(void)loadNewTopics{
    
    
    [self.tableView.footer endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    self.params = params;
    
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *  task, id   responseObject) {
        
        if (self.params != params) {
            return ;
        }
        
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        self.topics = [OSTopic objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        NSLog(@"%@",responseObject[@"list"]);
        
        [self.tableView reloadData];
        
        [self.tableView.header endRefreshing];
        
        self.page =  0 ;
        
        
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        if (self.params == params) {
            return ;
        }
        [self.tableView.footer endRefreshing];
    }];
    
    
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tableView.footer.hidden = (self.topics.count == 0);
    
    return self.topics.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     OSTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:OSTopicCellId ];
    cell.topic = self.topics[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    /*
    if (self.type == OSTopicTypeVideo) {
        [cell.videoView.playButton addTarget:self action:@selector(playClick:indexPath:) forControlEvents:UIControlEventTouchUpInside];
        cell.videoView.playButton.tag = indexPath.row;
        
        if (indexPath == currentIndexPath) {
            [cell.videoView.playButton.superview sendSubviewToBack:cell.videoView.playButton];
        }else{
            [cell.videoView.superview bringSubviewToFront:cell.videoView.playButton];
        }
        NSArray *indexpaths = [tableView indexPathsForVisibleRows];
        if (![indexpaths containsObject:currentIndexPath]) {
            if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:wmPlayer]) {
                wmPlayer.hidden = NO;
            }else{
                wmPlayer.hidden = YES;
                [cell.videoView.superview bringSubviewToFront:cell.videoView.playButton];
            }
        }else{
            if ([cell.videoView.subviews containsObject:wmPlayer]) {
                [cell.videoView addSubview:wmPlayer];
                [wmPlayer.player play];
                wmPlayer.playOrPauseBtn.selected = NO;
                wmPlayer.hidden = NO;
            }
        }
        
    }
    
    */
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OSCommentViewController *commentVc = [[OSCommentViewController alloc]init];
    commentVc.topic = self.topics[indexPath.row];
    [self.navigationController pushViewController:commentVc animated:YES];
}
/*
-(void)playClick:(UIButton *)button{
    
    currentIndexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
    self.currentCell = (OSTopicCell *)button.superview.superview;
    isSmallScreen = NO;
    
    OSTopic *top = self.topics[currentIndexPath.row];
    if (wmPlayer) {
        [wmPlayer removeFromSuperview];
        [wmPlayer setVideoURLStr:top.videouri];
        [wmPlayer.player play];
    }else{
        wmPlayer = [[WMPlayer alloc]initWithFrame:self.currentCell.videoView.imageView.frame videoURLStr:top.videouri];
        [wmPlayer.player play];
    }
    
    [self.currentCell.videoView addSubview:wmPlayer];
    [self.tableView reloadData];
    
    
    
}
*/
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    OSTopic *topic = self.topics[indexPath.row];
    
    return topic.cellHeight;
}


@end
